package top.maybesix.base.base

import android.content.Context
import android.os.Bundle
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.IdRes
import androidx.fragment.app.Fragment
import top.maybesix.base.action.BundleAction
import top.maybesix.base.action.ClickAction
import top.maybesix.base.action.HandlerAction

/**
 * @author MaybeSix
 * @date 2020/3/18
 * @desc TODO.
 */
abstract class BaseFragment<A : BaseActivity> : Fragment(),
    IFragment, HandlerAction, ClickAction, BundleAction {

    /** Activity 对象  */
    private var mActivity: A? = null

    /** 根布局  */
    private var mRootView: View? = null

    /** 是否初始化过  */
    private var mInitialize = false

    @Suppress("UNCHECKED_CAST")
    override fun onAttach(context: Context) {
        super.onAttach(context)
        // 获得全局的 Activity
        mActivity = requireActivity() as A
    }

    override fun onDetach() {
        mActivity = null
        super.onDetach()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        if (mRootView == null && getLayoutId() > 0) {
            mRootView = inflater.inflate(getLayoutId(), null)
        }
        mRootView?.parent?.let {
            val parent = it as ViewGroup
            parent.removeView(mRootView)
        }

        return mRootView

    }

    override fun onResume() {
        super.onResume()
        if (!mInitialize) {
            mInitialize = true
            initFragment()
        }
    }

    override fun getView(): View {
        return mRootView!!
    }

    /**
     * 获取绑定的 Activity，防止出现 getActivity 为空
     */
    public fun getAttachActivity(): A {
        return mActivity!!
    }

    protected open fun initFragment() {
        initBefore()
        initView()
        initEvent()
        initAdapter()
        initListener()
        initData()
    }


    override fun getBundle(): Bundle? {
        return arguments
    }

    /**
     * 根据资源 id 获取一个 View 对象
     */
    override fun <V : View> findViewById(@IdRes id: Int): V {
        return mRootView!!.findViewById(id)
    }

    /**
     * 销毁当前 Fragment 所在的 Activity
     */
    open fun finish() {
        if (mActivity != null && mActivity!!.isFinishing) {
            mActivity!!.finish()
        }
    }

    /**
     * Fragment 返回键被按下时回调
     */
    open fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        // 默认不拦截按键事件，回传给 Activity
        return false
    }
}